package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class indexController {
    @Autowired
    CategoryService categoryService;
    @Autowired
    private RedissonClient redisson;
    @GetMapping({"/","/index.html"})
    public  String indexPage(Model model){
        System.out.println(Thread.currentThread().getId());
        //TODO 1.查出所有的一级分类
        List<CategoryEntity> categoryEntityList=categoryService.getLevel1Categorys();
        //视图解析器进行拼串；
        model.addAttribute("categorys",categoryEntityList);
        return "index";
    }
    @ResponseBody
    @GetMapping("/index/catelog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJson(){
        Map<String, List<Catelog2Vo>> map=categoryService.getCatalogJson();
        return map;
    }
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        //1.获取一把锁，只要锁的名字一样，就是同一把锁
        RLock lock = redisson.getLock("my-lock");
        //2.加锁
        lock.lock(10, TimeUnit.SECONDS);//10s自动解锁，自动解锁时间一定要大于业务执行时间
        //问题lock.lock(10, TimeUnit.SECONDS);在锁时间到了以后不会自动续期。
        //1.如果我们传递了锁的超时时间，就发送给redis执行脚本，进行占锁，默认超时就是我们指定时间
        //2.如果我们未指定锁的超时时间，就使用30*1000【LockWatchdogTimeout看门狗的默认时间】
        //internalLockLeaseTame[看门狗时间]/3，10s

        //1）.锁的自动续期，如果业务超长，运行期间自动给锁续上新的30s
        try {
            System.out.println("加锁成功 执行业务..."+Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //3.解锁 假设解锁代码没有执行，redisson会不会出现死锁
            System.out.println("释放锁..."+Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }
}
